/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.camachosanchez.gui;

import com.camachosanchez.bean.Despinches;
import com.camachosanchez.bean.DetalleDespinche;
import com.camachosanchez.bean.InsumosDespinche;
import com.camachosanchez.bean.Neumaticos;
import com.camachosanchez.bean.Pilotos;
import com.camachosanchez.gui.combo.MyComboBoxEditor;
import com.camachosanchez.gui.combo.MyComboBoxRenderer;
import com.camachosanchez.util.Constantes;
import com.camachosanchez.util.GUIUtil;
import com.camachosanchez.util.JPAUtil;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

/**
 *
 * @author ZULLY
 */
public class DespincheNeumaticos extends javax.swing.JDialog {

    private EntityManagerFactory emf;
    private String[] insumos;
    private Neumaticos neumatico;

    /**
     * Creates new form DespincheNeumaticos
     */
    public DespincheNeumaticos(java.awt.Frame parent, boolean modal, Neumaticos neumatico) {
        super(parent, modal);
        initComponents();
        this.neumatico = neumatico;
        emf = JPAUtil.getEntityManagerFactory();
        GUIUtil.addEscapeKey(this);
        setLocationRelativeTo(null);
        setModal(modal);
        cargarCombos();
        cargarComboInsumos();
        tabla.setAnchoColumnas();
        dateFecha.setDate(new Date());
        cargarDatosVehiculo();
    }

    private void cargarCombos() {
        List<Pilotos> pilotos = new ArrayList<Pilotos>();
        try {
            Query q = JPAUtil.getEntityManagerFactory().createEntityManager().createNamedQuery("Pilotos.findByEstado");
            q.setParameter("estado", true);//lista los activos
            pilotos = q.getResultList();
        } catch (Exception e) {
            JOptionPane.showMessageDialog(Principal.getInstance(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
        if (pilotos.isEmpty()) {
            JOptionPane.showMessageDialog(this, "Se necesita por lo menos un piloto registrado para realizar un despinche, ingréselo desde el menú Logística.", "Datos incompletos", JOptionPane.WARNING_MESSAGE);
            return;
        }
        cmbPilotos.setModel(new DefaultComboBoxModel(pilotos.toArray()));
    }

    private void cargarComboInsumos() {
        tabla.insumosObject = new ArrayList<InsumosDespinche>();
        try {
            Query q = JPAUtil.getEntityManagerFactory().createEntityManager().createNamedQuery("InsumosDespinche.findByEstado");
            q.setParameter("estado", true);//lista los activos
            tabla.insumosObject = q.getResultList();
        } catch (Exception e) {
            JOptionPane.showMessageDialog(Principal.getInstance(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
        if (tabla.insumosObject.isEmpty()) {
            btnGuardar.setEnabled(false);
            JOptionPane.showMessageDialog(this, "Se necesita por lo menos un insumo de despinche registrado, ingréselo desde el menú Logística.", "Datos incompletos", JOptionPane.WARNING_MESSAGE);
        }
        insumos = new String[tabla.insumosObject.size()];
        Collections.sort(tabla.insumosObject);
        int i = 0;
        for (InsumosDespinche item : tabla.insumosObject) {
            insumos[i++] = item.getNombre();
        }
        TableColumn col = tabla.getColumnModel(0);
        col.setCellEditor(new MyComboBoxEditor(insumos));
        col.setCellRenderer(new MyComboBoxRenderer(insumos));
    }

    private void cargarDatosVehiculo() {
        if (neumatico.getIdCategoria().getId() == 2) {//categoría: Montado
            EntityManager em = emf.createEntityManager();
            Query q = em.createQuery("SELECT C.idVehiculo.placa, D.posicion FROM DetalleControlCambioNeumatico D"
                    + " JOIN D.idControlCambioNeumatico C"
                    + " WHERE D.idNeumatico.id = :idNeumatico ORDER BY C.id DESC");
            q.setParameter("idNeumatico", neumatico.getId());
            q.setMaxResults(1);
            List resultL = q.getResultList();
            String placa = "";
            Integer posicion = 0;
            if (!resultL.isEmpty()) {
                Object[] tupla = (Object[]) resultL.get(0);
                placa = (String) tupla[0];
                posicion = (Integer) tupla[1];
            }
            txtPlaca.setText(placa);
            txtPosicion.setText((posicion <= 0) ? "R" : posicion + "");
        }
        txtCodigo.setText(neumatico.getCodigo());
        if (neumatico.getIdModelo() != null) {
            txtDimension.setText(neumatico.getIdModelo().getMedida());
        }
        if (neumatico.getIdBandaInicial() != null) {
            txtBandaOriginal.setText(neumatico.getIdBandaInicial().getNombre());
        }
        txtRenovaciones.setText(neumatico.getNumRenovaciones() + "");
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnlToolBar = new javax.swing.JPanel();
        btnGuardar = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtCodigo = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txtPlaca = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        txtPosicion = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        txtDimension = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        txtRenovaciones = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        txtBandaOriginal = new javax.swing.JTextField();
        jPanel3 = new javax.swing.JPanel();
        jLabel7 = new javax.swing.JLabel();
        dateFecha = new com.toedter.calendar.JDateChooser();
        jLabel8 = new javax.swing.JLabel();
        txtKilometraje = new javax.swing.JTextField();
        jLabel11 = new javax.swing.JLabel();
        cmbPilotos = new javax.swing.JComboBox();
        pnlTablaInsumos = new javax.swing.JPanel();
        pnlOpciones = new javax.swing.JPanel();
        btnAgregar = new javax.swing.JButton();
        btnEliminar = new javax.swing.JButton();
        btlLimpiar = new javax.swing.JButton();
        tabla = new com.camachosanchez.gui.table.TablaDespinches();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle(".:: Despinche de neumático ::.");
        setResizable(false);

        pnlToolBar.setBackground(new java.awt.Color(255, 255, 255));
        pnlToolBar.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));

        btnGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/camachosanchez/recursos/24_save.png"))); // NOI18N
        btnGuardar.setToolTipText("Guardar");
        btnGuardar.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        btnGuardar.setFocusable(false);
        btnGuardar.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnGuardar.setMaximumSize(new java.awt.Dimension(22, 22));
        btnGuardar.setMinimumSize(new java.awt.Dimension(22, 22));
        btnGuardar.setPreferredSize(new java.awt.Dimension(22, 22));
        btnGuardar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarActionPerformed(evt);
            }
        });
        pnlToolBar.add(btnGuardar);

        getContentPane().add(pnlToolBar, java.awt.BorderLayout.PAGE_START);

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Neumático"));
        jPanel2.setLayout(new java.awt.GridLayout(2, 6, 5, 5));

        jLabel1.setText("Código:");
        jPanel2.add(jLabel1);

        txtCodigo.setEditable(false);
        jPanel2.add(txtCodigo);

        jLabel2.setText("Vehículo:");
        jPanel2.add(jLabel2);

        txtPlaca.setEditable(false);
        jPanel2.add(txtPlaca);

        jLabel3.setText("Posición:");
        jPanel2.add(jLabel3);

        txtPosicion.setEditable(false);
        jPanel2.add(txtPosicion);

        jLabel4.setText("Dimensión:");
        jPanel2.add(jLabel4);

        txtDimension.setEditable(false);
        jPanel2.add(txtDimension);

        jLabel5.setText("N° Renovaciones:");
        jPanel2.add(jLabel5);

        txtRenovaciones.setEditable(false);
        jPanel2.add(txtRenovaciones);

        jLabel6.setText("Banda Original:");
        jPanel2.add(jLabel6);

        txtBandaOriginal.setEditable(false);
        jPanel2.add(txtBandaOriginal);

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Información de Despinche"));
        jPanel3.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));

        jLabel7.setText("Fecha:");
        jPanel3.add(jLabel7);

        dateFecha.setDateFormatString("dd/MM/yyyy");
        dateFecha.setMaxSelectableDate(new Date());
        jPanel3.add(dateFecha);

        jLabel8.setText("Kilometraje:");
        jPanel3.add(jLabel8);

        txtKilometraje.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        txtKilometraje.setText("0");
        txtKilometraje.setPreferredSize(new java.awt.Dimension(100, 20));
        txtKilometraje.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtKilometrajeKeyTyped(evt);
            }
        });
        jPanel3.add(txtKilometraje);

        jLabel11.setText("Piloto:");
        jPanel3.add(jLabel11);

        cmbPilotos.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cmbPilotos.setPreferredSize(new java.awt.Dimension(200, 20));
        jPanel3.add(cmbPilotos);

        pnlTablaInsumos.setBorder(javax.swing.BorderFactory.createTitledBorder("Insumos"));
        pnlTablaInsumos.setOpaque(false);
        pnlTablaInsumos.setLayout(new java.awt.BorderLayout(2, 0));

        pnlOpciones.setOpaque(false);
        pnlOpciones.setLayout(new javax.swing.BoxLayout(pnlOpciones, javax.swing.BoxLayout.PAGE_AXIS));

        btnAgregar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/camachosanchez/recursos/12_add.png"))); // NOI18N
        btnAgregar.setBorder(null);
        btnAgregar.setMaximumSize(new java.awt.Dimension(21, 21));
        btnAgregar.setMinimumSize(new java.awt.Dimension(21, 21));
        btnAgregar.setOpaque(false);
        btnAgregar.setPreferredSize(new java.awt.Dimension(21, 21));
        btnAgregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAgregarActionPerformed(evt);
            }
        });
        pnlOpciones.add(btnAgregar);

        btnEliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/camachosanchez/recursos/12_delete.png"))); // NOI18N
        btnEliminar.setBorder(null);
        btnEliminar.setMaximumSize(new java.awt.Dimension(21, 21));
        btnEliminar.setMinimumSize(new java.awt.Dimension(21, 21));
        btnEliminar.setOpaque(false);
        btnEliminar.setPreferredSize(new java.awt.Dimension(21, 21));
        btnEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarActionPerformed(evt);
            }
        });
        pnlOpciones.add(btnEliminar);

        btlLimpiar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/camachosanchez/recursos/12_clear.png"))); // NOI18N
        btlLimpiar.setBorder(null);
        btlLimpiar.setMaximumSize(new java.awt.Dimension(21, 21));
        btlLimpiar.setMinimumSize(new java.awt.Dimension(21, 21));
        btlLimpiar.setOpaque(false);
        btlLimpiar.setPreferredSize(new java.awt.Dimension(21, 21));
        btlLimpiar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btlLimpiarActionPerformed(evt);
            }
        });
        pnlOpciones.add(btlLimpiar);

        pnlTablaInsumos.add(pnlOpciones, java.awt.BorderLayout.LINE_END);
        pnlTablaInsumos.add(tabla, java.awt.BorderLayout.CENTER);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(pnlTablaInsumos, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 609, Short.MAX_VALUE)
                    .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, 609, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, 609, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(pnlTablaInsumos, javax.swing.GroupLayout.DEFAULT_SIZE, 196, Short.MAX_VALUE)
                .addContainerGap())
        );

        getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed
        // TODO add your handling code here:
        tabla.cancelarEdicionCelda();
        guardar();
    }//GEN-LAST:event_btnGuardarActionPerformed

    private void btlLimpiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btlLimpiarActionPerformed
        // TODO add your handling code here:
        tabla.cancelarEdicionCelda();
        tabla.limpiarTabla();
    }//GEN-LAST:event_btlLimpiarActionPerformed

    private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarActionPerformed
        // TODO add your handling code here:
        tabla.cancelarEdicionCelda();
        tabla.deleteRow();
    }//GEN-LAST:event_btnEliminarActionPerformed

    private void btnAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAgregarActionPerformed
        // TODO add your handling code here:
        if (insumos != null && insumos.length > 0) {
            Object[] obj = new Object[5];
            obj[0] = insumos[0];
            obj[1] = tabla.insumosObject.get(0).getCodigo();
            obj[2] = "0";
            obj[3] = "0.0";
            obj[4] = "0.00";
            tabla.addRow(obj);
        }
        tabla.setAnchoColumnas();
    }//GEN-LAST:event_btnAgregarActionPerformed

    private void txtKilometrajeKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtKilometrajeKeyTyped
        // TODO add your handling code here:
        char caracter = evt.getKeyChar();
        String caracteres = txtKilometraje.getText();
        if (!(Character.isDigit(caracter)) || (caracteres.length() >= 10)) {
            evt.consume();
        }
    }//GEN-LAST:event_txtKilometrajeKeyTyped

    private void guardar() {
        if (validarDatos()) {
            EntityManager em = null;
            try {
                em = emf.createEntityManager();
                em.getTransaction().begin();
                Despinches despinche = new Despinches();
                despinche.setFecha(dateFecha.getDate());
                try {
                    despinche.setKmVehiculo(Long.parseLong(txtKilometraje.getText()));
                } catch (NumberFormatException e) {
                    JOptionPane.showMessageDialog(this, "El kilometraje ingresado no es correcto.", "Datos incorrectos", JOptionPane.WARNING_MESSAGE);
                    txtKilometraje.requestFocusInWindow();
                    return;
                }
                despinche.setIdNeumaticos(neumatico);
                despinche.setIdPilotos((Pilotos) cmbPilotos.getSelectedItem());
                despinche.setIdUsuarios(Constantes.currentUser);
                List<DetalleDespinche> detalle = new ArrayList<DetalleDespinche>();
                DefaultTableModel datos = tabla.getData();
                int tam = datos.getRowCount();
                for (int i = 0; i < tam; i++) {
                    DetalleDespinche item = new DetalleDespinche();
                    String nombreInsumo = datos.getValueAt(i, 0).toString();
                    int index = Collections.binarySearch(tabla.insumosObject, new InsumosDespinche(Short.valueOf("0"), 0, nombreInsumo, true));
                    InsumosDespinche insumo = tabla.insumosObject.get(index);
                    item.setIdInsumosDespinche(insumo);
                    Short cantidad;
                    try {
                        cantidad = Short.parseShort(datos.getValueAt(i, 2).toString());
                    } catch (NumberFormatException ex) {
                        JOptionPane.showMessageDialog(this, "El valor de la cantidad en la fila " + (i + 1) + " no es el correcto.", "Datos incorrectos", JOptionPane.WARNING_MESSAGE);
                        return;
                    }
                    if (cantidad == 0) {
                        JOptionPane.showMessageDialog(this, "Ingrese la cantidad en la fila " + (i + 1) + ".", "Datos incorrectos", JOptionPane.WARNING_MESSAGE);
                        return;
                    }
                    item.setCantidad(cantidad);
                    double costoUnit;
                    try {
                        costoUnit = Double.parseDouble(datos.getValueAt(i, 3).toString());
                    } catch (NumberFormatException ex) {
                        JOptionPane.showMessageDialog(this, "El valor del costo unitario en la fila " + (i + 1) + " no es el correcto.", "Datos incorrectos", JOptionPane.WARNING_MESSAGE);
                        return;
                    }
                    if (costoUnit == 0) {
                        JOptionPane.showMessageDialog(this, "Ingrese el costo unitario en la fila " + (i + 1) + ".", "Datos incorrectos", JOptionPane.WARNING_MESSAGE);
                        return;
                    }
                    item.setCostoUnitario(costoUnit);
                    item.setCostoTotal(Double.parseDouble(datos.getValueAt(i, 4).toString()));
                    detalle.add(item);
                }

                for (DetalleDespinche d : detalle) {
                    d.setIdDespinches(despinche);
                }
                despinche.setDetalleDespincheList(detalle);
                em.persist(despinche);
                em.flush();
                em.refresh(despinche);
                em.getTransaction().commit();
                JOptionPane.showMessageDialog(this, "El registro de despinche de neumáticos ha finalizado correctamente.", "Operación finalizada", JOptionPane.INFORMATION_MESSAGE);
                dispose();

            } catch (Exception e) {
                if (em.getTransaction().isActive()) {
                    em.getTransaction().rollback();
                }
                JOptionPane.showMessageDialog(Principal.getInstance(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
            } finally {
                if (em != null) {
                    em.close();
                }
            }
        }
    }

    private boolean validarDatos() {
        if (dateFecha.getDate() == null) {
            JOptionPane.showMessageDialog(this, "Ingrese una fecha válida.", "Datos incorrectos", JOptionPane.WARNING_MESSAGE);
            dateFecha.requestFocusInWindow();
            return false;
        }
        if ((txtKilometraje.getText()).equals("")) {
            JOptionPane.showMessageDialog(this, "Ingrese un kilometraje válido.", "Datos incorrectos", JOptionPane.WARNING_MESSAGE);
            txtKilometraje.requestFocusInWindow();
            return false;
        }
        if (tabla.getData().getRowCount() == 0) {
            JOptionPane.showMessageDialog(this, "Ingrese al menos un insumo utilizado en el despinche.", "Datos incorrectos", JOptionPane.WARNING_MESSAGE);
            btnAgregar.requestFocusInWindow();
            return false;
        }
        if (tabla.total == 0) {
            JOptionPane.showMessageDialog(this, "Ingrese la cantidad y precio unitario completo del insumo.", "Datos incorrectos", JOptionPane.WARNING_MESSAGE);
            tabla.requestFocusInWindow();
            return false;
        }
        return true;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btlLimpiar;
    private javax.swing.JButton btnAgregar;
    private javax.swing.JButton btnEliminar;
    private javax.swing.JButton btnGuardar;
    private javax.swing.JComboBox cmbPilotos;
    private com.toedter.calendar.JDateChooser dateFecha;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel pnlOpciones;
    private javax.swing.JPanel pnlTablaInsumos;
    private javax.swing.JPanel pnlToolBar;
    private com.camachosanchez.gui.table.TablaDespinches tabla;
    private javax.swing.JTextField txtBandaOriginal;
    private javax.swing.JTextField txtCodigo;
    private javax.swing.JTextField txtDimension;
    private javax.swing.JTextField txtKilometraje;
    private javax.swing.JTextField txtPlaca;
    private javax.swing.JTextField txtPosicion;
    private javax.swing.JTextField txtRenovaciones;
    // End of variables declaration//GEN-END:variables
}
